package de.fh.ka.as.car.drivecontrol;

import java.io.IOException;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryonet.Client;

import de.fh.ka.as.car.CarPreferences;
import de.fh.ka.as.car.drivecontrol.model.Car;
import de.fh.ka.as.car.drivecontrol.model.Control;

public class RemoteCar extends Activity implements Car {

	private Client client;
	private Kryo kryo;

	public static final int PORT = 5000;

	@Override
	public void control(Control control) {
		client.sendTCP(control);
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		CanvasView canvasView = new CanvasView(this, this);
		setContentView(canvasView);
		startClient();
	}

	public void onDestroy() {
		super.onDestroy();

		// close network connection
		if (client.isConnected())
			client.close();
	}

	public void startClient() {
		client = new Client();
		client.start();

		try {
			Log.i("IOIONetwork", "Client connect to: " + CarPreferences.getIP_ADDRESS() + " on Port: " + PORT);
			client.connect(PORT, CarPreferences.getIP_ADDRESS(), 54555, 54777);
		} catch (IOException e) {
			e.printStackTrace();
		}

		kryo = client.getKryo();
		kryo.register(Control.class);
	}

}
